<?php
/**
 * Created by PhpStorm.
 * User: jacob
 * Date: 18-7-26
 * Time: 下午4:29
 */
namespace DB;

use MongoDB\Driver\Cursor;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Query;
use Tiny\Logger;

class Mongodb{
    private static $manager = null;
    private $dbname;
    private $colname;

    public function __construct(string $colname,string $dbname = null) {
      $this->dbname = $dbname ?? \Config\Mongodb::Mongodb_dbname;
      $this->colname = $colname;
    }

    /**
     * 获取数据库连接对象
     * @return Manager
     */
    public function getManager():Manager {
      if (self::$manager == null){
        Logger::getInstance()->debug("开始连接mongodb");
        try{
          $uri = "mongodb://".\Config\Mongodb::Mongodb_username.":".
            \Config\Mongodb::Mongodb_password."@".\Config\Mongodb::Mongodb_host."
            :".\Config\Mongodb::Mongodb_port."/".\Config\Mongodb::Mongodb_dbname;
          self::$manager = new Manager($uri);
        }catch (\Exception $e){
          Logger::getInstance()->debug("连接失败：".$e->getMessage());
        }
        Logger::getInstance()->debug("连接结束");
      }

      return self::$manager;
    }

    /**获取数据库名.集合名
     * @return string
     */
    public function getNamespace():string {
      return $this->dbname.".".$this->colname;
    }

    /**
     * 获取数据库名
     * @return string
     */
    public function getDbName():string {
      return $this->dbname;
    }

    /**
     * 获取集合名
     * @return string
     */
    public function getColName():string {
      return $this->colname;
    }

    public function getMany(array $filter=[],array $options=[]):Cursor{
      $manager = $this->getManager();
      return $manager->executeQuery($this->getNamespace(),new Query($filter,$options));
    }

}
